<?php
namespace app\api\controller\v1;
use app\api\controller\Fun;
use app\api\repository\UserRepository;
use app\api\service\UserService;
use app\api\service\WxService;
use app\common\Model\User;
use app\common\Model\UserShaohuo;
use app\common\Server\Captcha;
use app\common\Server\Redis;
use app\common\Server\Validate;
use think\Config;


/**
 * @title 登陆类接口V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class Login extends Base
{
    static public $validate = [

        'loginOrregister' => [
            'base' => [
                'type' => 'type',
                'source' => 'source'
            ],
            'status' => [
                [
                    'key' => ['type','source'],
                    'value' =>[
                        [
                            'rule'=>[
                                'type'=>'login',
                                'source' => 'mobile'
                            ],
                            'valid'=>[
                                'mobile' => 'mobile',
                                'captcha' => 'captcha'
                            ]
                        ],
                        [
                            'rule' => [
                                'type' => 'login',
                                'source' => 'wx'
                            ],
                            'valid' => [
                                'code' => 'code'
                            ]
                        ],
                        [
                            'rule' => [
                                'type' => 'bind',
                                'source' => 'wx'
                            ],
                            'valid' => [
                                'mobile' => 'mobile',
                                'captcha' => 'captcha',
                                'openid' => 'openid',
                                'unionid' => 'unionid'
                            ]
                        ]

                    ]
                ],
            ],
            'relation' => [
            ]

        ],
        'sendCaptcha' => [
            'base' => [
                'mobile' => 'mobile',
                'type' => 'type'
            ],
            'status' => [
                [
                    'key' => ['type'],
                    'value' => [
                        [
                            'rule' => [
                                'type' => 'bind'
                            ],
                            'valid' => [
                                'source' => 'source'
                            ]
                        ],
                        [
                            'rule' => [
                                'type' => 'unbind'
                            ],
                            'valid' => [
                                'source' => 'source'
                            ]
                        ],
                    ]
                ],
            ]
        ]
    ];


    const PREFIX = 'CACHE:CAPTCAH:%s';

    /**
     * @title 登录或注册用户
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Login desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:loginOrregister desc:登录或注册
     * @param name:type type:string require:1 default: other:login|bind|unbind desc:登陆|绑定|解绑
     * @param name:source type:string require:1 default: other:mobile|wx|qq|wb desc:手机登陆|微信登陆
     * @param name:mobile type:string require:0 default: other:18900000000 desc:手机号
     * @param name:code type:string require:0 default: other:021qGlrT16LLo71Ro6pT17r2rT1qGlrk desc:微信登陆code
     * @param name:captcha type:string require:0 default: other:8888 desc:验证码
     * @param name:openid type:string require:0 default: other:ow2qP0gjmO0AqYujrC2OU5OqQybg desc:绑定手机号微信openid
     * @param name:unionid type:string require:0 default: other:ow2qP0gjmO0AqYujrC2OU5OqQybg desc:绑定手机号微信unionid
     * @param name:client type:string require:0 default:dl other:miniprogram|pay desc:客户端代码
     * @param name:app_name type:string require:0 default:'' other:shr desc:客户端名称，捎货人app必传shr
     *
//     * @return data:[]
     */
    public function loginOrregister()
    {
        $this->arr['client'] = $this->arr['client'] ?? 'dl';
        extract($this->arr);
        //第三方登陆
        if($type == 'login' && $source != 'mobile'){

            if($source == 'wx'){
                $encryptedData = $this->arr['encryptedData'] ?? '';
                $iv = $this->arr['iv'] ?? '';
                $res = WxService::instance()->getInfoByCode($code,$client,$encryptedData,$iv);
                if(!$res){
                    return Fun::error('801001',WxService::$data['errmsg']);
                }

                $openid = WxService::$data['openid'];
                $unionid = WxService::$data['unionid'];

                $data = [
                    'openid' => $openid,
                    'unionid' => $unionid
                ];
                $this->arr += $data;
            }else{
                return Fun::error('801009');
            }
            //查询用户数据
            $user_res = UserService::instance()->loginOrregister($this->arr,'thirdlogin');
        //手机登陆|第三方绑定|第三方解绑
        }else{
            //验证验证码
            if(!$captcha = $this->arr['captcha'] ?? ''){
                return Fun::error('999993');
            }else{
                $redis = new Redis();
                $ckey  = sprintf(self::PREFIX, $mobile);

                $redis_captcha = $redis->get($ckey);
                if(($redis_captcha != $captcha) &&
                    $this->arr['mobile'] !== '13900000000' &&
                    $this->arr['mobile'] !== '13800000000' &&
                    $this->arr['mobile'] !== '13700000000' &&
                    $this->arr['mobile'] !== '13600000000' &&
                    $this->arr['mobile'] !== '13500000000'
                ){
                    return Fun::error('801000');
                }
            }
            //查询用户数据
            $user_res = UserService::instance()->loginOrregister($this->arr);
        }

//        $app_id = Config::get('wx_'.$this->arr['client'].'.app_id');

        //如果是捎货人登陆，验证捎货人状态
        if(($app_name ?? '') === 'shr'){
            if($uid = UserService::$data['uid'] ?? ''){
                $data = ['is_shr' => '1'];
                $shaohuoren = UserShaohuo::get(['uid' => $uid]);
                if(empty($shaohuoren) || $shaohuoren->status == 0){
                    $data = ['is_shr' => '0'];
                }
                $data += UserService::$data;
                $aliyun_oss = Config::get('aliyun_oss');
                unset($aliyun_oss['img_url']);
                $data += $aliyun_oss;
                return Fun::success($data);
            }
        }

        if($user_res) {
            //登陆成功返回aliyun_oss配置，需要绑定不返回该信息
            $aliyun_oss = Config::get('aliyun_oss');
            unset($aliyun_oss['img_url']);
            UserService::$data += $aliyun_oss;
//            UserService::$data['openid'] = UserService::$data['openid'][$app_id] ?? '';
            return Fun::success(UserService::$data,'登陆成功');
        }elseif ((UserService::$data['is_reg'] ?? 0)){
            //不需要绑定是返回配置信息
            $aliyun_oss = Config::get('aliyun_oss');
            unset($aliyun_oss['img_url']);
            UserService::$data += $aliyun_oss;
//            UserService::$data['openid'] = UserService::$data['openid'][$app_id] ?? '';
            return Fun::success(UserService::$data, '登陆成功');
        }else{
            return Fun::error(UserService::$data['err']);
        }
    }

    /**
     * @title 发送验证码
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Login desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:sendCaptcha desc:发送验证码
     * @param name:mobile type:string require:1 default: other:18900000000 desc:手机号
     * @param name:type type:string require:1 default: other:login登陆|bind绑定|unbind解绑 desc:请求类型
     * @param name:source type:string require:0 default: other:wx desc:绑定解绑必传 来源 wx..
     * @param name:is_voice type:string require:0 default: other:wx desc:是否语音验证码0否1是
     *
     * @return data:[]
     */
    public function sendCaptcha()
    {
        extract($this->arr);
        $is_voice = empty($is_voice) ? 0 : 1;

        $relation = [
            'wx' => 'unionid',
        ];

        //非登陆且无绑定解绑来源
        if($type != 'login' && !($relation[$source] ?? '')){
            return Fun::error('801007');
        }

        //验证手机号
        $mobile = Validate::instance()->getPhone($mobile);
        if(!$mobile){
            return Fun::error('801004');
        }

        //绑定验证
        if($type == 'bind'){
            $user = User::get(['mobile' => $mobile]);
            //验证绑定
            if (!empty($user->{$relation[$source]})){
                return Fun::error('801006');
            }
        }

        //发送验证码
        $rtn = Captcha::instance()->send($mobile,$is_voice);

        if($rtn === true){
            return Fun::success([],'发送成功');
        }else{
            return Fun::error(Captcha::$data['err'] ?? '');
        }
    }
}